#!/usr/bin/env python
#
#  DB.py
#
#  Copyright (C) 2008 Johnny Jacob <johnnyjacob@gmail.com>
#
#  THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: 
#
#  Permission is hereby granted, free of charge, to any person obtaining a
#  copy of this software and associated documentation files (the "Software"),  
#  to deal in the Software without restriction, including without limitation  
#  the rights to use, copy, modify, merge, publish, distribute, sublicense,  
#  and/or sell copies of the Software, and to permit persons to whom the  
#  Software is furnished to do so, subject to the following conditions:
#
#  The above copyright notice and this permission notice shall be included in 
#  all copies or substantial portions of the Software.
#
#  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
#  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
#  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
#  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
#  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
#  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
#  DEALINGS IN THE SOFTWARE.
#

import sqlite3
import datetime
import os
import time

class DB:
    __single = None   #Singleton class 

    __app_data_path = os.environ['HOME'] + "/.percipien/"
    __db_path = __app_data_path + "events.db"

    def adapt_datetime (self, ts):
        return time.mktime(ts.timetuple())

    def record (self, stime, etime, appname, title):
        print "Recording"
        self.cursor.execute('INSERT INTO events VALUES (?,?,?,?)',(stime, etime, appname, title))
        self.connection.commit ()

    def __create_db_tables (self):
        print "DEBUG : __create_db_tables"
        self.cursor.execute('CREATE TABLE events (stime INTEGER PRIMARY KEY, etime INTEGER, appname VARCHAR(50), title VARCHAR(100))')

    def __init__(self):
        if DB.__single:
            raise DB.__single
        DB.__single = self

        sqlite3.register_adapter(datetime.datetime, self.adapt_datetime)

        if not os.path.isfile (DB.__db_path) : 
            os.mkdir (DB.__app_data_path)
            self.connection = sqlite3.connect (DB.__db_path)
            self.cursor = self.connection.cursor()
            self.__create_db_tables ()
        else :
            self.connection = sqlite3.connect (DB.__db_path)
            self.cursor = self.connection.cursor()

